import BaseCURDApi from '@/framework/infra/base/BaseCURDApi'
import SpuProperty from '@/feature/pdt/domain/SpuProperty'
import SpuPropertyCollection from '@/feature/pdt/domain/SpuPropertyCollection'
import SpuDetailEntity from "@/feature/pdt/domain/SpuDetailEntity";
import {propertyApi} from './propertyApi'

class CategoryApi extends BaseCURDApi {
  constructor() {
    super('spu/category')
  }

  backList(parentId = null) {
    return this.get('back-list', {parentId})
  }

  search(keywords) {
    return this.get('search', {keywords}).then(data => {
      if (data && data.length) {
        data.forEach(items => {
          items.forEach(item => {
            item.title = item.title.replaceAll(keywords, '<i>' + keywords + '</i>')
          })
        })
      }
      return data
    })
  }

  detail(id) {
    return this.get('detail', {id}).then(async data => {
      data.propList = SpuPropertyCollection.from(data.propList.map(el => new SpuProperty(el, false)))
      if (data.salePropList && data.salePropList.length) {
        data.salePropSource = 0
        data.salePropList = SpuPropertyCollection.from(data.salePropList.map(el => new SpuProperty(el, true)), true)
      } else {
        data.salePropSource = 1
        data.salePropList = SpuPropertyCollection.from([], true, null, await propertyApi.commonSaleProps())
      }
      return new SpuDetailEntity(data)
    })
  }

  firstCateList() {
    return this.backList().then(data => {
      const map = data.reduce((r, a) => {
        r[a.stapleName] = r[a.stapleName] || []
        r[a.stapleName].push(a)
        return r
      }, {})
      return Object.keys(map).reduce((r, a) => {
        r.push({title: a, list: map[a]})
        return r
      }, [])
    })
  }

  subCateList(parentId) {
    return this.backList(parentId).then(data => {
      const map = data.reduce((r, a) => {
        r[a.firstLetter] = r[a.firstLetter] || []
        r[a.firstLetter].push(a)
        return r
      }, {})
      return Object.keys(map).reduce((r, a) => {
        map[a][0].isFirst = !!map[a][0].firstLetter
        r.push(...map[a])
        return r
      }, [])
    })
  }
}

export const categoryApi = new CategoryApi()
